<?php

namespace App\Models\Guanyuan;

use App\Models\BaseModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageMappingModel;
use App\Models\OpenShop\Organization\OpenShopRegionManageModel;
use App\Service\Kms\Home\HomeService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;

class GuanyuanSyncShopBusinessModel extends BaseModel
{
    use HasFactory;

    protected $table = 'guanyuan_sync_shop_business';

    protected $fillable = [
        'placementType',
        'placementStartDate',
        'businessType',
        'name',
        'code',
        'region',
        'date',
        'orderNum',
        'isMonthNew',
        'dailyArtificial',
        'dailyEnergy',
        'roi',
        'estimatedProfit',
        'openingDurationMonth',
        'openingDurationDay',
        'area',
        'orderTurnover',
        'orderDiscountAmount',
        'orderReceivedAmount',
        'employeesNum',
        'province',
        'city',
        'takeawayTurnover',
        'takeawayDiscountAmount',
        'takeawayReceivedAmount',
        'dineInTurnover',
        'dineInDiscountAmount',
        'dineInReceivedAmount',
        'dineInEstimatedProfit',
        'takeawayEstimatedProfit',
        'takeawayOrderNum',
        'dineInOrderNum',
        'openBusinessDate',
        'closeDate',
        'franchiseeName',
        'dailyRent',
        'rent',
        'district',
        'storeActiveStatus',
        'status',
        'artificial',
        'breakEvenPoint',
        'monthlyBusinessDays',
        'dailyReceivedAmount',
        'monthlyDays',
        'isCloseShop',
        'address',
        'cityGrade',
        'reArea',
        'roiType',
        'vipCardTurnover',
        'vipCardDiscountAmount',
        'vipCardReceivedAmount',
        'vipCardOrderNum',
        'franchiseeRealName',
        'dailyRentCost',
        'elmTurnover',
        'elmDiscountAmount',
        'elmReceivedAmount',
        'elmOrderNum',
        'mtTurnover',
        'mtDiscountAmount',
        'mtReceivedAmount',
        'mtOrderNum',
        'operationManager',
        'privateDomain',
        'operationalStatus',
        'averageDailyProfit',
        'receiptGrading',
        'ProfitClassification',
        'weightRoi',
        'whetherLoss',
        'shopGrade',
        'siteLocationType',
        'elmRating',
        'mtRating',
        'mtStoreId',
        'elmStoreId',
        'cashierSystem',
        'elmStar1',
        'elmStar2',
        'elmStar3',
        'elmStar4',
        'elmStar5',
        'mtStar1',
        'mtStar2',
        'mtStar3',
        'mtStar4',
        'mtStar5',
        'elmWaimaiShopId',
        'elmWaimaiShopName',
        'mtWaimaiShopId',
        'mtWaimaiShopName',
        'takeawayStartTime',
        'takeawayOldOrNew',
        'performanceRanges',
        'activityType',
        'storeType',
        'takeawayBusinessDays',
        'temperatureMax',
        'temperatureMin',
        'recentAttention',
        'nightWeather',
        'noonWeather',
        'developmentManager',
        'operationSupervision',
        'keyCity',
        'relocationMark',
        'elmRepurchaseRate',
        'elmBusinessCirclePeerMean',
        'elmBusinessCirclePeerMeanTop10',
        'mtRepurchaseRate',
        'mtBusinessCirclePeerMean',
        'mtBusinessCirclePeerMeanTop10',
        'secondaryLeader',
        'mallGrade',
        'createdAt',
        'updatedAt',
    ];

    /**
     * 首页查询条件构造
     *
     * @param int $regionSelectionType
     * @param string $region
     * @return Builder
     */
    public static function buildHomeSearchQuery(int $regionSelectionType, string $region): Builder
    {
        switch ($regionSelectionType) {
            case HomeService::REGION_SELECTION_TYPE_1:
                $query = function ($query) use ($region) {
//                    return $query->where("region", "LIKE", "%" . str_replace("分公司", "", $region) . "%");
                    $organizationModel = OpenShopOrganizationManageModel::query()
                                                                        ->with("regionRel")
                                                                        ->where("name", $region)
                                                                        ->first();

                    if($organizationModel && $organizationModel->regionRel){
                        return $query->whereIn("province", $organizationModel->regionRel->pluck("provinceName")->toArray());
                    }else{
                        return $query->where("province", "-1");
                    }
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_2:
                $query = function ($query) use ($region) {
                    return $query->where("province", $region);
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_3:
                $query = function ($query) use ($region) {
                    return $query->where("city", $region);
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_4:
                $query = function ($query) use ($region) {
                    $provinceNames = [];
                    $warRegionRow = OpenShopRegionManageModel::query()
                                                             ->with([
                                                                 "regionMappingRel"     => function ($query) {
                                                                     $query->with(["organizationManageRel" => function($query){
                                                                         $query->with("regionRel");
                                                                     }]);
                                                                 }
                                                             ])->where("name", $region)->first();

                    $warRegionRow->regionMappingRel->each(function (OpenShopRegionManageMappingModel $manageMappingModel) use (&$provinceNames) {
                        $provinceNames = array_merge(
                            $provinceNames,
                            $manageMappingModel->organizationManageRel->regionRel->pluck("provinceName")->toArray()
                        );
                    });

                    if($provinceNames){
                        return $query->whereIn("province", $provinceNames);
                    }else{
                        return $query->where("province", "-1");
                    }
                };
                break;
            case HomeService::REGION_SELECTION_TYPE_0:
            default:
                $query = null;
                break;
        }
        return self::query()->where("region", "!=", "国外店")
                   ->when($query, function ($subQuery) use ($query) { return $subQuery->where($query); });
    }
}
